package com.mogujie.tt.ui.fragment;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.Selection;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.TextAppearanceSpan;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.mogujie.tt.DB.sp.LoginSp;
import com.mogujie.tt.R;
import com.mogujie.tt.config.SysConstant;
import com.mogujie.tt.imservice.event.DetaiLsEvent;
import com.mogujie.tt.ui.adapter.MypotoGridViewitemAdapter;
import com.mogujie.tt.ui.adapter.QuanzQzImageAdapter;
import com.mogujie.tt.ui.adapter.QuanzQzReplyAdapter;
import com.mogujie.tt.ui.base.TTBaseFragment;
import com.mogujie.tt.ui.helper.Emoparser;
import com.mogujie.tt.ui.widget.EmoGridView;
import com.mogujie.tt.ui.widget.PublishLayout;
import com.mogujie.tt.ui.widget.QuanzDynamicImageGridView;
import com.mogujie.tt.ui.widget.QuanzQzPhone;
import com.mogujie.tt.ui.widget.QuanzQzReply;
import com.mogujie.tt.ui.widget.QuanzQzReplyListView;
import com.mogujie.tt.utils.GETUtil;
import com.nostra13.universalimageloader.core.ImageLoader;

import org.json.JSONArray;
import org.json.JSONObject;

import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import de.greenrobot.event.EventBus;

/**
 * Created by Administrator on 2015/12/3.
 */
public class QzMyPhotoDetailsFragment extends TTBaseFragment implements View.OnClickListener,PublishLayout.SoftListener {
    private View curView = null;
    private String first;
    private ImageView photo;//头像
    private TextView content_text;//要发表的文字
    private QuanzDynamicImageGridView image_content;//发表的图片
    private TextView favuor_name;//显示谁点赞
    private TextView delete;//删除
    private ImageButton reply_icon;//弹出点赞 评论
    private QuanzQzReplyListView reply_list;//回复
    private EditText reply;
    private ImageView reply_emo_btn;
    private TextView send_reply;
    private View reply_favour;
    private TextView name;
    private TextView Timedata;
    private View LLdetails;
    private ProgressBar progress_bar;
    private View RRR;
    private View emo_layout_publish;
    int rootBottom = Integer.MIN_VALUE, keyboardHeight = 0;
    private InputMethodManager inputManager = null;
    private EmoGridView emoGridView = null;
    private Map<String,QuanzQzReply> map = null;
    private Map<String,Map<String,QuanzQzReply>> map1 = null;
    private QuanzQzReplyAdapter quanzQzReplyAdapter;
    private ArrayList<QuanzQzReply> list_reply=null;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup vg, Bundle bundle) {
        try {
            if (null != curView) {
                ((ViewGroup) curView.getParent()).removeView(curView);
                return curView;
            }
            curView = inflater.inflate(R.layout.quanz_details_fragment, topContentView);
            inputManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
            findLayout();
            initRes();
            getUrlsll();
            return curView;
        }catch (Exception e){
            System.out.println("1111111QzMyPhotoDetailsFragment   " + e.getMessage());
        }
        return null;
    }

    private void findLayout() {

        photo = (ImageView) curView.findViewById(R.id.photo);
        content_text = (TextView) curView.findViewById(R.id.content_text);
        image_content = (QuanzDynamicImageGridView) curView.findViewById(R.id.image_content);
        favuor_name = (TextView) curView.findViewById(R.id.favuor_name);
        delete = (TextView) curView.findViewById(R.id.delete);
        delete.setOnClickListener(this);
        reply_icon = (ImageButton) curView.findViewById(R.id.reply_icon);
        reply_list = (QuanzQzReplyListView) curView.findViewById(R.id.reply_list);
        reply = (EditText) curView.findViewById(R.id.reply);
        reply.setOnClickListener(this);
        reply_emo_btn = (ImageView) curView.findViewById(R.id.reply_emo_btn);
        reply_emo_btn.setOnClickListener(this);
        send_reply = (TextView) curView.findViewById(R.id.send_reply);
        send_reply.setOnClickListener(this);
        reply_favour = curView.findViewById(R.id.reply_favour);
        reply_favour.setVisibility(View.GONE);
        name = (TextView) curView.findViewById(R.id.name);
        Timedata = (TextView) curView.findViewById(R.id.date);
        progress_bar = (ProgressBar) curView.findViewById(R.id.progress_bar);
        RRR = curView.findViewById(R.id.RRR);
        RRR.setOnClickListener(this);
        emo_layout_publish = curView.findViewById(R.id.emo_layout_publish);
        emoGridView = (EmoGridView) curView.findViewById(R.id.emo_gridview_publish);
        LLdetails = curView.findViewById(R.id.LLdetails);
        LinearLayout.LayoutParams paramEmoLayout = (LinearLayout.LayoutParams) emo_layout_publish.getLayoutParams();
        if (keyboardHeight > 0) {
            paramEmoLayout.height = keyboardHeight;
            emo_layout_publish.setLayoutParams(paramEmoLayout);
        }
        emoGridView.setOnEmoGridViewItemClick(onEmoGridViewItemClick);
        emoGridView.setAdapter();
    }

    private void initRes() {
        setTopTitle("详情");
        setTopLeftButton(R.drawable.tt_top_back);
        topLeftContainerLayout.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                getActivity().finish();
            }
        });
        setTopLeftText(getResources().getString(R.string.top_left_back));
    }

    @Override
    protected void initHandler() {

    }

    private String login_name;
    private String login_password;
    public void getUrlsll() {
        login_name = LoginSp.instance().getLoginIdentity().getLoginName();
        login_password = LoginSp.instance().getLoginIdentity().getPwd();

        new AsyncTask<String, Void, Object>() {
            protected void onPostExecute(Object result) {
                super.onPostExecute(result);
                progress_bar.setVisibility(View.GONE);
                RRR.setVisibility(View.VISIBLE);
                System.out.println("7788888888 "+result.toString());
                if (result.toString()==null||"".equals(result.toString())){
                    return;
                }
                try {
                    JSONObject res = new JSONObject(result.toString());
                    JSONObject data = res.getJSONObject("data");
                    if ("".equals(data.toString())||data.toString()==null){
                        return;
                    }
                    content_text.setText(Emoparser.getInstance(getActivity()).emoCharsequence(data.getString("content")));
                    name.setText(data.getString("uname"));
                    Timedata.setText(handTime(data.getString("ctime") + ":00"));

                    list_reply = new ArrayList<QuanzQzReply>();
                    if (map.size()==0){
                        reply_list.setVisibility(View.GONE);
                    }else {
                        for (int i=0;i<map.size();i++){
                           list_reply.add(map.get(i+""));
                        }
                        quanzQzReplyAdapter = new QuanzQzReplyAdapter(getActivity(),new Quanzflush());
                        quanzQzReplyAdapter.setData(list_reply);
                        reply_list.setAdapter(quanzQzReplyAdapter);
                    }

                    if (data.getString("type").equals("postimage")){
                        ArrayList<QuanzQzPhone> list = getPhotos(data.getString("attach"));
                        if (list != null) {
                            image_content.setAdapter(new QuanzQzImageAdapter(getActivity(), list, false));
                            image_content.setOnItemClickListener(new AdapterView.OnItemClickListener() {  // 设置监听器 ，点击进入大图
                                @Override
                                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                }
                            });
                        }
                    }

                    ImageLoader.getInstance().displayImage(data.getString("avatar_big").replace("\\", ""), photo);

                    if (!data.getString("diggs").equals("null")){
                        System.out.println("778888222");
                        if (!data.getString("diggs").equals("[]")){
                            reply_favour.setVisibility(View.VISIBLE);
                            JSONArray diggs = data.getJSONArray("diggs");
                            String mName="";
                            JSONObject nick=null;
                            for (int i=0;i<diggs.length();i++){
                                nick=diggs.getJSONObject(i);
                                JSONObject user=nick.getJSONObject("user");
                                if (mName!=""){
                                    if (user.getString("uid").equals(String.valueOf(LoginSp.instance().getLoginIdentity().getLoginId()))){
                                        mName=user.getString("nick")+"、"+mName;
                                    }else{
                                        mName=mName+"、"+user.getString("nick");
                                    }
                                }else{
                                    mName=user.getString("nick");
                                }
                            }
                            String[] favour = mName.split("、");
                            String fav="";
                            String fav1="";
                            if (favour.length>5){
                                if (fav!=""){
                                    for (int i=1;i<5;i++){
                                        fav=fav+"、"+favour[i];
                                    }
                                    fav1="等"+favour.length+"人觉的很赞";
                                }else {
                                    fav=" "+favour[0];
                                }
                            }else{
                                fav=mName;
                                fav1="觉得很赞";
                            }

                            SpannableString styledText = new SpannableString(fav+fav1);
                            styledText.setSpan(new TextAppearanceSpan(getActivity(), R.style.style0), 0, fav.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                            styledText.setSpan(new TextAppearanceSpan(getActivity(), R.style.style1), fav.length(),fav.length()+ fav1.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                            favuor_name.setText(styledText,TextView.BufferType.SPANNABLE);

                        }

                    }
                } catch (Exception e) {

                }
            }
            protected Object doInBackground(String... params) {
                String result = GETUtil.instance().sendGet(GETUtil.instance().getRequestText("public", "Index", "getFeedInfo", login_name, login_password, String.valueOf(MypotoGridViewitemAdapter.feed_Id),null,null,null,null,null,null));
                CommentReply();
                return result;
            }
        }.execute();
    }


    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private String handTime(String time) {
        if (time == null || "".equals(time.trim())) {
            return "";
        }
        try {
            Date date = format.parse(time);
            long tm = System.currentTimeMillis();// 当前时间戳
            long tm2 = date.getTime();// 发表动态的时间戳
            long d = (tm - tm2) / 1000;// 时间差距 单位秒
            if ((d / (60 * 60 * 24)) > 0) {
                return d / (60 * 60 * 24) + "天前";
            } else if ((d / (60 * 60)) > 0) {
                return d / (60 * 60) + "小时前";
            } else if ((d / 60) > 0) {
                return d / 60 + "分钟前";
            } else {
                // return d + "秒前";
                return "刚刚";
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            System.out.println("1111111Qz  " + e.getMessage());
        }
        return null;
    }

    private ArrayList<QuanzQzPhone> getPhotos(String photo) {
        if (!photo.contains("[")) {
            return null;
        }
        ArrayList<QuanzQzPhone> phs = new ArrayList<QuanzQzPhone>();
        try {
            JSONArray array = new JSONArray(photo);
            int size = array.length();
            JSONObject obj;
            QuanzQzPhone ph;
            for (int i = 0; i < size; i++) {
                obj = array.getJSONObject(i);
                ph = new QuanzQzPhone();
                ph.min = obj.getString("attach_small");
                ph.max = obj.getString("attach_url");
                phs.add(ph);
            }
            return phs;
        } catch (Exception e) {
            System.out.println("1111111Qz  " + e.getMessage());
        }
        return null;
    }

    @Override
    public void onClick(final View view) {
        switch (view.getId()){
            case R.id.reply_emo_btn:

                if (emo_layout_publish.getVisibility() == View.VISIBLE) {
                    if (!reply.hasFocus()) {
                        reply.requestFocus();
                    }
                    emo_layout_publish.setVisibility(View.GONE);
                    inputManager.toggleSoftInputFromWindow(reply.getWindowToken(), 1, 0);
                    if (keyboardHeight == 0) {
                        emo_layout_publish.setVisibility(View.GONE);
                    }
                }else if (emo_layout_publish.getVisibility() == View.GONE) {
                    inputManager.hideSoftInputFromWindow(reply.getWindowToken(), 0);
                    emo_layout_publish.setVisibility(View.VISIBLE);
                    emoGridView.setVisibility(View.VISIBLE);
                }
                if(reply.isFocused()){
                    //已获得焦点
                }else{
                    reply.requestFocus();//获得焦点
                }

                break;
            case R.id.RRR:
                InputMethodManager imm = (InputMethodManager)
                        getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
                emo_layout_publish.setVisibility(View.GONE);
                LLdetails.setVisibility(View.GONE);
                RRR.setEnabled(false);
                break;
            case R.id.reply:
                emo_layout_publish.setVisibility(View.GONE);
                break;
            case R.id.delete:

                AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(getActivity(), android.R.style.Theme_Holo_Light_Dialog));
                LayoutInflater inflater = (LayoutInflater)getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                View dialog_view = inflater.inflate(R.layout.tt_custom_dialog, null);
                final EditText editText = (EditText)dialog_view.findViewById(R.id.dialog_edit_content);
                editText.setVisibility(View.GONE);
                TextView textText = (TextView)dialog_view.findViewById(R.id.dialog_title);
                textText.setText("确认删除？");
                builder.setView(dialog_view);
                builder.setPositiveButton(getActivity().getString(R.string.tt_ok), new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        new AsyncTask<String, Void, Object>() {
                            protected void onPostExecute(Object result) {
                                super.onPostExecute(result);
                                try {
                                    JSONObject status = new JSONObject(result.toString());
                                    if ("1".equals(status.getString("status"))) {
                                        Toast.makeText(getActivity(), "删除成功", Toast.LENGTH_SHORT);
                                        triggerEvent(DetaiLsEvent.SUCCEED);
                                        getActivity().finish();
                                    } else {
                                        Toast.makeText(getActivity(), "删除失败，" + status.getString("msg"), Toast.LENGTH_SHORT);
                                    }
                                } catch (Exception e) {
                                    System.out.println("1111111Qz  " + e.getMessage());
                                }
                            }

                            protected Object doInBackground(String... params) {
                                String result = GETUtil.instance().sendGet(GETUtil.instance().getRequestText("public", "Index", "removeFeed",
                                        login_name, login_password, String.valueOf(MypotoGridViewitemAdapter.feed_Id), null, null, null, null, null, null));
                                return result;
                            }
                        }.execute();
                        dialog.dismiss();
                    }
                });
                builder.setNegativeButton(getActivity().getString(R.string.tt_cancel), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                    }
                });
                builder.show();

                break;
            case R.id.send_reply:

                final String o_edit = "回复@"+DsendName+"："+reply.getText().toString();
                final String vo_feed_id = String.valueOf(Df_feed_id);
                final String o_replyName = DsendName;
                if (TextUtils.isEmpty(reply.getText().toString())){
                    Toast.makeText(getActivity(),"请输入。。。",Toast.LENGTH_SHORT).show();
                    return;
                }
                Log.i("sxun", "send btn is click" + reply.getText().toString());
                new AsyncTask<String, Void, Object>() {
                    protected void onPostExecute(Object result) {
                        super.onPostExecute(result);
                        InputMethodManager imm = (InputMethodManager)
                                getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
                        emo_layout_publish.setVisibility(View.GONE);
                        LLdetails.setVisibility(View.GONE);
                        RRR.setEnabled(false);
                        try {
                            JSONObject status = new JSONObject(result.toString());
                            System.out.println("4444444455566="+status);
                            if (status.getString("status").equals("1")){
                                JSONObject data = status.getJSONObject("data");
                                JSONObject result1 = data.getJSONObject("result");
                                JSONObject user_info = result1.getJSONObject("user_info");
                                QuanzQzReply reply1  = new QuanzQzReply();
                                reply1.content = reply.getText().toString();
                                reply1.replyName = o_replyName;
                                reply1.userId = user_info.getString("uid");
                                reply1.friendId = Integer.valueOf(result1.getString("comment_id"));//就是在回复数据库中的id  ***
                                reply1.id = Integer.valueOf(result1.getString("row_id"));
                                reply1.sendName = user_info.getString("nick");
                                reply1.f_friendId = Integer.valueOf(vo_feed_id);
                                list_reply.add(0, reply1);
                                quanzQzReplyAdapter.notifyDataSetChanged();
                                reply.setText("");
                            }else if (status.getString("status").equals("0")){
                                Toast.makeText(getActivity(),"评论失败",Toast.LENGTH_SHORT).show();
                            }
                        } catch (Exception e) {
                            System.out.println("1111111Qz  " + e.getMessage());
                        }
                    }
                    protected Object doInBackground(String... params) {

                        String result = null;
                        try {
                            result = GETUtil.instance().sendGet(GETUtil.instance().getRequestText1("public", "Index", "addcomment",
                                    login_name, login_password, "public", "feed",String.valueOf(LoginSp.instance().getLoginIdentity().getLoginId())
                                    ,vo_feed_id, Dto_feed_id, Dto_uid, URLEncoder.encode(o_edit, "GBK")));
                            return result;
                        } catch (Exception e) {
                            System.out.println("1111111Qz  " + e.getMessage());
                        }
                        return "";
                    }
                }.execute();


                break;

        }
    }
    public void triggerEvent(DetaiLsEvent event) {
        EventBus.getDefault().postSticky(event);
    }
    @Override
    public void onSoftChange(PublishLayout.SoftState softState, int softHeight) {
        Log.d("sxun", "SoftState:" + softState + ";softHeight:" + softHeight);
        PublishLayout.SoftState keyboard_show = softState;
        if (softState == PublishLayout.SoftState.SHOW && softHeight >0) {
            keyboardHeight = softHeight;
            LinearLayout.LayoutParams paramEmoLayout = (LinearLayout.LayoutParams) emo_layout_publish.getLayoutParams();
            if (keyboardHeight > 0) {
                paramEmoLayout.height = keyboardHeight;
                emo_layout_publish.setLayoutParams(paramEmoLayout);
            }
        }
    }

    private EmoGridView.OnEmoGridViewItemClick onEmoGridViewItemClick = new EmoGridView.OnEmoGridViewItemClick() {
        @Override
        public void onItemClick(int facesPos, int viewIndex) {
            int deleteId = (++viewIndex) * (SysConstant.pageSize - 1);
            if (deleteId > Emoparser.getInstance(getActivity()).getResIdList().length) {
                deleteId = Emoparser.getInstance(getActivity()).getResIdList().length;
            }
            if (deleteId == facesPos) {
                String msgContent = reply.getText().toString();
                if (msgContent.isEmpty())
                    return;
                if (msgContent.contains("["))
                    msgContent = msgContent.substring(0, msgContent.lastIndexOf("["));
                reply.setText(msgContent);
            } else {
                int resId = Emoparser.getInstance(getActivity()).getResIdList()[facesPos];
                String pharse = Emoparser.getInstance(getActivity()).getIdPhraseMap()
                        .get(resId);
                int startIndex = reply.getSelectionStart();
                Editable edit = reply.getEditableText();
                if (startIndex < 0 || startIndex >= edit.length()) {
                    if (null != pharse) {
                        edit.append(pharse);
                    }
                } else {
                    if (null != pharse) {
                        edit.insert(startIndex, pharse);
                    }
                }
            }
            Editable edtable = reply.getText();
            int position = edtable.length();
            Selection.setSelection(edtable, position);
        }
    };

    private void CommentReply(){
        try {
            String Feed_for_comments = GETUtil.instance().sendGet(GETUtil.instance().getRequestText("public", "Index", "getComment", login_name, login_password, String.valueOf(MypotoGridViewitemAdapter.feed_Id), null, null, null, null, null, ""));
            JSONObject JFeed_for_comments = new JSONObject(Feed_for_comments);
            String Jdata = JFeed_for_comments.getString("data");
            map = new HashMap<String,QuanzQzReply>();
            if (Jdata.equals("")){

            }else{
                JSONArray Jdata1 = new JSONArray(Jdata);
                int Jbz=0;
                for (int j=0;j<Jdata1.length();j++){
                    JSONObject Jobj= Jdata1.getJSONObject(j);
                    JSONObject user_info=Jobj.getJSONObject("user_info");
                    String content = Jobj.getString("content");
                    QuanzQzReply reply  = new QuanzQzReply();
                    if (content.indexOf("@")>0){
                        reply.content = content.split("：")[1];
                        JSONObject to_uid_user_info = Jobj.getJSONObject("to_uid_user_info");//这里是回复了谁的详细信息
                        reply.replyName = content.split("：")[0].split("@")[1];//获取回复谁的名字
                    }else{
                        reply.content = content;
                        reply.replyName = "";
                    }
                    reply.userId = Jobj.getString("uid");
                    reply.friendId =Integer.valueOf(Jobj.getString("comment_id"));//就是在回复数据库中的id  ***
                    reply.id = Integer.valueOf(Jobj.getString("row_id"));
                    reply.sendName = user_info.getString("nick");
                    reply.f_friendId = Integer.valueOf(String.valueOf(MypotoGridViewitemAdapter.feed_Id));
                    map.put(Jbz+"",reply);//feed_id
                    System.out.println("77888888Feed_for_comments=" + map);
                    Jbz++;
                }
            }
        }catch (Exception e) {
            System.out.println("1111111Qz  " + e.getMessage());
        }
    }

    private String DsendName;
    private int Dpos;
    private String Dto_feed_id;
    private String Dto_uid;
    private String Df_feed_id;

    public class Quanzflush implements QuanzQzReplyAdapter.FlushListView1 {

        @Override
        public void flush(int pos,String to_feed_id,String to_uid,String f_feed_id,String sendName,View v) {
            LLdetails.setVisibility(View.VISIBLE);
            RRR.setEnabled(true);
            System.out.println("77888888Feed_for_comments=" + pos + "  " + to_feed_id + "   " + f_feed_id);
            DsendName = sendName;
            Dpos = pos;
            Dto_feed_id = to_feed_id;
            Dto_uid = to_uid;
            Df_feed_id = f_feed_id;

        }

        @Override
        public void flushmesshage(View v) {
        }

        @Override
        public void flushdetails() {
        }

    }

}
